package cn.yzgy.yzgyoa.common.service.impl;

import cn.yzgy.yzgyoa.common.dto.SysFileInfoDto;
import cn.yzgy.yzgyoa.common.entity.SysFileInfo;
import cn.yzgy.yzgyoa.common.mapper.SysFileInfoMapper;
import cn.yzgy.yzgyoa.common.service.ISysFileInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Yqsen
 * @since 2021-11-03
 */
@Service
public class SysFileInfoServiceImpl extends ServiceImpl<SysFileInfoMapper, SysFileInfo> implements ISysFileInfoService {

    @Override
    public IPage<SysFileInfoDto> getAllFiles(Page<Object> page, SysFileInfoDto queryDto) {
        return baseMapper.getAllFiles(page,queryDto);
    }

    @Override
    public boolean delFile(SysFileInfo queryDto) {
        SysFileInfo sysFileInfo = new SysFileInfo().selectOne(
                new QueryWrapper<SysFileInfo>().lambda().eq(SysFileInfo::getFileId,queryDto.getFileId()));
        String path= sysFileInfo.getFilePath();
        File file = new File(path);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return sysFileInfo.deleteById();
            } else {
                //启动jvm垃圾回收
                System.gc();
                if(file.delete()){
                    return sysFileInfo.deleteById();
                }else{
                    return false;
                }
            }
        } else {
            return false;
        }
    }

    @Override
    public boolean delFiles(String busiId) {
        List<SysFileInfo> sysFileInfoList = new SysFileInfo()
                .setBusiId(Long.parseLong(busiId))
                .selectList(new QueryWrapper<SysFileInfo>()
                        .lambda().eq(SysFileInfo::getBusiId, busiId));
        for (SysFileInfo sysFileInfo : sysFileInfoList) {
            delFile(sysFileInfo);
        }
        return  true;
    }


}
